package com.shauvik.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

public abstract class IOCountdown implements EntryPoint {
	public AbsolutePanel aPanel;
	private Timer countdownTimer;
	private long timeToIO;
	private int[] digits={-1,-1,-1,-1,-1,-1,-1,-1,-1};
	List<Widget[][]> pointers = new ArrayList<Widget[][]>();

	@Override
	public void onModuleLoad() {
		countdownTimer = new Timer() {
			public void run() {
				updateCountdown();
			}
		};
		//Google IO would be start on 2011 May 10th at 9:00 am
		long ioDate = new Date(2011-1900, 5-1, 10, 9, 0, 0).getTime();
		timeToIO = ioDate - System.currentTimeMillis();
		countdownTimer.scheduleRepeating(1000);
		populateNumbers();
		initAnimation();
	}
	
	public void initAnimation(){
		//specialize
	}

	public void populateNumbers()  {
		HorizontalPanel hPanel = new HorizontalPanel();
	    hPanel.setSpacing(5);

	    hPanel.add(buildNumber(0,"blue"));
	    hPanel.add(buildNumber(1,"blue"));
	    hPanel.add(buildNumber(2,"blue"));
	    
	    addSeparator(hPanel);	    
	    
	    hPanel.add(buildNumber(3,"cyan"));
	    hPanel.add(buildNumber(4,"cyan"));
	    
	    addSeparator(hPanel);
	    
	    hPanel.add(buildNumber(5,"red"));
	    hPanel.add(buildNumber(6,"red"));
	    
	    addSeparator(hPanel);
	    
	    hPanel.add(buildNumber(7,"green"));
	    hPanel.add(buildNumber(8,"green"));

		aPanel = new AbsolutePanel();
		aPanel.add(hPanel);
		
		RootPanel.get("main").add(aPanel);
		
	}

	public void addSeparator(HorizontalPanel hPanel) {
		Widget sep = buildSeparator();
	    hPanel.add(sep);
	    hPanel.setCellVerticalAlignment(sep, HasVerticalAlignment.ALIGN_MIDDLE);
	}
	
	abstract public Widget buildSeparator();
	abstract public Widget buildNumber(int id, String style);

	private void updateCountdown() {
		int [] old_digits = new int [9];
		for(int i=0;i<9;i++){ //Deep copy
			old_digits[i]=digits[i];
		}
		timeToIO -= 1000;
		extractTime(timeToIO);
		animate(old_digits, digits);
	}
	
	abstract public void animate(int[] old_digits, int[] digits);

	private void extractTime(long timestamp){
		long time = timestamp / 1000;
		int secs = (int) time % 60;
		int min = (int) (time % (3600)) / 60;
		int hrs = (int) (time % (24*3600)) / 3600;
		int days = (int) time / (24*3600);
		digits[0]=days/100;
		digits[1]=(days%100)/10;
		digits[2]=days%10;
		digits[3]=hrs/10;
		digits[4]=hrs%10;
		digits[5]=min/10;
		digits[6]=min%10;
		digits[7]=secs/10;
		digits[8]=secs%10;
	}

}
